﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WebSocketSharp;
using WebSocketSharp.Server;

public class AppManager : MonoBehaviour {
    private static AppManager m_Instance;
    public static AppManager Insatnce
    {
        get { return m_Instance; }
    }



    private static Dictionary<string, WebSocketServer> servers = new Dictionary<string, WebSocketServer>();



    private void Awake()
    {
        m_Instance = this;


    }
    // Use this for initialization
    void Start () {
        WebSocketServer server = new WebSocketServer(AppConst._Address);
        server.WaitTime = TimeSpan.FromSeconds(2);
        server.AddWebSocketService<MessageHandle>(AppConst._TestPath);
        server.Start();
        servers.Add(AppConst._Address, server);
        Debug.Log("服务器开启成功");
    }
	




}

public class MessageHandle:WebSocketBehavior
{
    private string addr { get { return base.Context.Host; } }

    /// <summary>
    /// 连接客户端调用
    /// </summary>
    protected override void OnOpen()
    {
        Debug.Log("Client Connected: " + ID);
        //   Form1.instance.Log(addr, "Client Connected: " + ID);
        // ShowPanel.Insatnce.CreatClientConnent("Client Connected: " + ID);
        ShowPanel.CreatClientConnent("Client Connected: " + ID);
        SendMessage("Connect at " + DateTime.Now);
    }
    /// <summary>
    /// 客户端发送消息调用
    /// </summary>
    /// <param name="e"></param>
    protected override void OnMessage(MessageEventArgs e)
    {
        string msg = e.Data;
      //  Form1.instance.Log(addr, "Receive From :" + ID + "\n" + msg);
        SendMessage("Got [" + msg + "] at " + DateTime.Now);
    }
    /// <summary>
    /// 关闭客户端调用
    /// </summary>
    /// <param name="e"></param>
    protected override void OnClose(CloseEventArgs e)
    {
      //  Form1.instance.Log(addr, "Client Closed :" + ID);
        Sessions.CloseSession(ID);
    }

    public void SendMessage(string msg)
    {
        Sessions.SendToAsync(msg, ID, (a) => { });
    }






}